#!/bin/sh
# Copyright (c) 2011, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.

# created on 2011-04-14

main() {
 local DOPING="1"
 QUICK=""
 if [ -n "$DOPING" ] ;then
#  local HOST=wifizone.hu
  local HOST=bkil.hu
  local IP=`dns_lookup $HOST`
  [ -z "$IP" ] && DOPING=""
  echo $IP >&2
 fi
 while true
 do
  if [ -n "$DOPING" ] ;then
   get_loss_time $IP
  else
   echo "100 0"
   if [ -n "$QUICK" ] ;then
    sleep 1
   else
    sleep 5
   fi
  fi |
  {
   read LOSS TIMEF
   TIME=`echo "$TIMEF" |
         sed "s~\..*$~~"` #truncate
   get_stats |
   {
    read BITRATE POWER LINK LINKMAX SIGNAL NOISE
    if [ -n "$BITRATE" ] && [ "$BITRATE" != "_" ]
    then
     local Q=`echo "$LINK $LINKMAX / 100 * p" |
        dc`
     local SNR=`expr $SIGNAL - $NOISE`

     printf "q%2.0f%% %2dM SNR%2ddB S%4ddBm N% 4ddBm %3dms loss%.0f%%\n" $Q $BITRATE $SNR $SIGNAL $NOISE $TIME $LOSS
    else
     printf "loss%.0f%%\n" $LOSS
    fi
   }
  }
 done
}

get_loss_time() {
 local IP=$1
 local WAIT=1
 if [ -z "$QUICK" ]; then
  local SENT=5
 else
  local SENT=1
 fi
 {
  sleep 0.1 # to make CTRL-C easier
  ping -q -c$SENT -W$WAIT $IP 2>&1 ||
   sleep 1
 } |
 grep -E "(% packet loss|round-trip)" |
 sed -r "
  s/^.*\<([0-9]*)% packet loss.*$/\1/
  s~^.*round-trip.*\<[0-9.]+/([0-9.]+)/[0-9.]+\>.*$~\1~
  " |
 {
  read LOSS
  read AVGTIME
  if [ -z "$AVGTIME" ] ;then
   AVGTIME=0
  fi
  echo $LOSS $AVGTIME
 }
}

dns_lookup() {
 local HOST=$1
 local RETRY=5
 while
  [ $RETRY -gt 0 ] && [ -z "$IP" ]
 do
  IP=`dns_lookup_ $HOST`
  if [ -z "$IP" ]
  then
   echo "retries left: $RETRY" >&2
   sleep 1
   RETRY=`expr $RETRY - 1`
  fi
 done
 [ -n "$IP" ] && echo "$IP"
}

dns_lookup_() {
 local HOST=$1
 local IP=`nc -zvw5 $HOST 80 2>&1 |
           sed -r "s/^.*\(([0-9.]+):[0-9]+\) .*$/\1/"`
 echo "$IP" |
 grep -v "\<bad address\>"
}

get_stats() {
 iwconfig 2>/dev/null |
 grep -E "(Tx-Power|Link)" |
 sed -r "
  s~^.*(\<[0-9]+) Mb/s.*Tx-Power=([0-9]+) dBm.*$~\1 \2~
  s~^.*Link Quality=([0-9]+)/([0-9]+).*Signal level=([-0-9]+) dBm *Noise level=([-0-9]+) dBm.*$~\1 \2 \3 \4~
  s~^.*Tx-Power=([0-9]+) dBm.*$~_ \1~
  s~^.*Link Quality=0 .*Signal level=0 .*Noise level=0 .*$~_ _ _ _~
  s~^.*Tx-Power=([0-9]+) dBm.*$~_ \1~
 " |
 {
  read BITRATE POWER
  read LINK LINKMAX SIGNAL NOISE
  echo $BITRATE $POWER $LINK $LINKMAX $SIGNAL $NOISE
 }
}

main "$@"
